const path = require('path')
const fs = require('fs')
const ejs = require('ejs')
const express = require('express')
const app = express();
const port = process.argv[2]?Number(process.argv[2].split("=")[1]):3000 //设置端口号
app.use(express.static(process.cwd())) //设置服务器指定目录
app.use((req, res, next) => {
    //判断务器指定目录是否存在
    if (fs.existsSync(process.cwd())) {
        let filePath = path.join(process.cwd(), decodeURIComponent(req.path))
        //获取知道目录路径
        if (!filePath.includes("favicon.ico")) {//是否存在图标
            let dirList = fs.readdirSync(filePath)//读取指定目录
            dirList = dirList.map(item => {
                return {
                    title: item,
                    path: item
                }
            })
            // 服务器端渲染页面=>前后端不分离
            let htmlView = fs.readFileSync(path.join(__dirname, 'index.html'), 'utf-8')
            res.send(ejs.render(htmlView, { dirList }))
        } else {
            console.log("图片走丢了")
        }
    }
})

app.listen(port, () => {
    console.log(`http://localhost:${port}`)
})